<template>
  <div class="member-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>会员管理</span>
          <div class="header-operations">
            <el-button type="primary" @click="handleAdd">新增会员</el-button>
            <el-button type="success" @click="handleExport">导出会员</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="会员等级" prop="level">
          <el-select v-model="queryParams.level" placeholder="请选择会员等级" clearable>
            <el-option
              v-for="item in memberLevels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="会员状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择会员状态" clearable>
            <el-option
              v-for="item in memberStatus"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="注册时间" prop="timeRange">
          <el-date-picker
            v-model="queryParams.timeRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="搜索关键词" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="会员姓名/手机号/会员号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 会员统计卡片 -->
      <el-row :gutter="20" class="statistics-cards">
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>会员总数</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.totalCount }}</div>
              <div class="label">人</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>本月新增</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.monthNewCount }}</div>
              <div class="label">人</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>活跃会员</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">{{ statistics.activeCount }}</div>
              <div class="label">人</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card shadow="hover">
            <template #header>
              <div class="card-header">
                <span>会员消费</span>
              </div>
            </template>
            <div class="statistics-content">
              <div class="amount">¥ {{ statistics.totalConsumption }}</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 会员列表 -->
      <el-table
        v-loading="loading"
        :data="memberList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column prop="memberNo" label="会员号" width="120" />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="120" />
        <el-table-column prop="level" label="会员等级" width="120">
          <template #default="{ row }">
            <el-tag :type="getMemberLevelTag(row.level)">
              {{ getMemberLevelLabel(row.level) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="points" label="积分" width="100" />
        <el-table-column prop="balance" label="余额" width="120">
          <template #default="{ row }">
            ¥ {{ row.balance?.toFixed(2) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getMemberStatusTag(row.status)">
              {{ getMemberStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="registerTime" label="注册时间" width="180" />
        <el-table-column prop="lastLoginTime" label="最后登录" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              @click="handleDetail(row)"
            >
              详情
            </el-button>
            <el-button
              link
              type="success"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="warning"
              @click="handlePoints(row)"
            >
              积分
            </el-button>
            <el-button
              link
              type="danger"
              @click="handleDisable(row)"
              v-if="row.status === 1"
            >
              禁用
            </el-button>
            <el-button
              link
              type="success"
              @click="handleEnable(row)"
              v-if="row.status === 0"
            >
              启用
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑会员对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增会员' : '编辑会员'"
      width="600px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="会员姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入会员姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="会员等级" prop="level">
          <el-select v-model="form.level" placeholder="请选择会员等级">
            <el-option
              v-for="item in memberLevels"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="初始积分" prop="points">
          <el-input-number
            v-model="form.points"
            :min="0"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="初始余额" prop="balance">
          <el-input-number
            v-model="form.balance"
            :min="0"
            :precision="2"
            :step="100"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 会员详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="会员详情"
      width="800px"
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="会员号">{{ detail.memberNo }}</el-descriptions-item>
        <el-descriptions-item label="会员姓名">{{ detail.name }}</el-descriptions-item>
        <el-descriptions-item label="手机号">{{ detail.phone }}</el-descriptions-item>
        <el-descriptions-item label="会员等级">
          <el-tag :type="getMemberLevelTag(detail.level)">
            {{ getMemberLevelLabel(detail.level) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="积分">{{ detail.points }}</el-descriptions-item>
        <el-descriptions-item label="余额">
          ¥ {{ detail.balance?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getMemberStatusTag(detail.status)">
            {{ getMemberStatusLabel(detail.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="注册时间">{{ detail.registerTime }}</el-descriptions-item>
        <el-descriptions-item label="最后登录">{{ detail.lastLoginTime }}</el-descriptions-item>
        <el-descriptions-item label="消费总额">
          ¥ {{ detail.totalConsumption?.toFixed(2) }}
        </el-descriptions-item>
        <el-descriptions-item label="订单数量">{{ detail.orderCount }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ detail.remark }}</el-descriptions-item>
      </el-descriptions>

      <!-- 消费记录 -->
      <div class="detail-section">
        <div class="section-title">消费记录</div>
        <el-table :data="detail.consumptionRecords" border>
          <el-table-column prop="orderNo" label="订单号" width="180" />
          <el-table-column prop="amount" label="消费金额" width="120">
            <template #default="{ row }">
              ¥ {{ row.amount?.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column prop="points" label="获得积分" width="100" />
          <el-table-column prop="createTime" label="消费时间" width="180" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>

      <!-- 积分记录 -->
      <div class="detail-section">
        <div class="section-title">积分记录</div>
        <el-table :data="detail.pointsRecords" border>
          <el-table-column prop="type" label="类型" width="120">
            <template #default="{ row }">
              <el-tag :type="row.type === 1 ? 'success' : 'danger'">
                {{ row.type === 1 ? '增加' : '减少' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="points" label="积分变动" width="120" />
          <el-table-column prop="balance" label="积分余额" width="120" />
          <el-table-column prop="createTime" label="变动时间" width="180" />
          <el-table-column prop="remark" label="备注" />
        </el-table>
      </div>
    </el-dialog>

    <!-- 积分操作对话框 -->
    <el-dialog
      v-model="pointsDialogVisible"
      title="积分操作"
      width="500px"
    >
      <el-form
        ref="pointsFormRef"
        :model="pointsForm"
        :rules="pointsRules"
        label-width="100px"
      >
        <el-form-item label="会员姓名">
          <span>{{ pointsForm.name }}</span>
        </el-form-item>
        <el-form-item label="当前积分">
          <span>{{ pointsForm.currentPoints }}</span>
        </el-form-item>
        <el-form-item label="操作类型" prop="type">
          <el-radio-group v-model="pointsForm.type">
            <el-radio :label="1">增加积分</el-radio>
            <el-radio :label="2">减少积分</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="积分数量" prop="points">
          <el-input-number
            v-model="pointsForm.points"
            :min="1"
            :precision="0"
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="pointsForm.remark"
            type="textarea"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="pointsDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPoints">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getMemberList, exportMemberList, getMemberStatistics, addMember, updateMember, updateMemberStatus, updateMemberPoints } from '@/api/member'

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  level: undefined,
  status: undefined,
  timeRange: [],
  keyword: ''
})

// 会员等级选项
const memberLevels = [
  { label: '普通会员', value: 'NORMAL' },
  { label: '银卡会员', value: 'SILVER' },
  { label: '金卡会员', value: 'GOLD' },
  { label: '钻石会员', value: 'DIAMOND' }
]

// 会员状态选项
const memberStatus = [
  { label: '正常', value: 1 },
  { label: '禁用', value: 0 }
]

// 统计数据
const statistics = ref({
  totalCount: 0,
  monthNewCount: 0,
  activeCount: 0,
  totalConsumption: 0
})

// 表格数据
const loading = ref(false)
const memberList = ref([])
const total = ref(0)

// 新增/编辑对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  name: '',
  phone: '',
  level: '',
  points: 0,
  balance: 0,
  remark: ''
})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入会员姓名', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  level: [
    { required: true, message: '请选择会员等级', trigger: 'change' }
  ]
}

// 详情对话框
const detailDialogVisible = ref(false)
const detail = ref({})

// 积分操作对话框
const pointsDialogVisible = ref(false)
const pointsFormRef = ref(null)
const pointsForm = ref({
  memberId: '',
  name: '',
  currentPoints: 0,
  type: 1,
  points: 0,
  remark: ''
})

// 积分表单验证规则
const pointsRules = {
  type: [
    { required: true, message: '请选择操作类型', trigger: 'change' }
  ],
  points: [
    { required: true, message: '请输入积分数量', trigger: 'blur' }
  ],
  remark: [
    { required: true, message: '请输入备注信息', trigger: 'blur' }
  ]
}

// 获取会员等级标签
const getMemberLevelTag = (level) => {
  const map = {
    NORMAL: 'info',
    SILVER: 'success',
    GOLD: 'warning',
    DIAMOND: 'danger'
  }
  return map[level] || 'info'
}

// 获取会员等级标签文本
const getMemberLevelLabel = (level) => {
  const item = memberLevels.find(item => item.value === level)
  return item ? item.label : level
}

// 获取会员状态标签
const getMemberStatusTag = (status) => {
  return status === 1 ? 'success' : 'danger'
}

// 获取会员状态标签文本
const getMemberStatusLabel = (status) => {
  const item = memberStatus.find(item => item.value === status)
  return item ? item.label : status
}

// 查询列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getMemberList(queryParams.value)
    memberList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取会员列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取统计数据
const getStatistics = async () => {
  try {
    const res = await getMemberStatistics()
    statistics.value = res.data
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

// 查询按钮点击
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList()
  getStatistics()
}

// 重置按钮点击
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    level: undefined,
    status: undefined,
    timeRange: [],
    keyword: ''
  }
  handleQuery()
}

// 导出按钮点击
const handleExport = async () => {
  try {
    const res = await exportMemberList(queryParams.value)
    const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = '会员列表.xlsx'
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  }
}

// 新增按钮点击
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    phone: '',
    level: '',
    points: 0,
    balance: 0,
    remark: ''
  }
  dialogVisible.value = true
}

// 编辑按钮点击
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = {
    id: row.id,
    name: row.name,
    phone: row.phone,
    level: row.level,
    points: row.points,
    balance: row.balance,
    remark: row.remark
  }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addMember(form.value)
          ElMessage.success('新增成功')
        } else {
          await updateMember(form.value)
          ElMessage.success('编辑成功')
        }
        dialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error(dialogType.value === 'add' ? '新增失败:' : '编辑失败:', error)
        ElMessage.error(dialogType.value === 'add' ? '新增失败' : '编辑失败')
      }
    }
  })
}

// 查看详情
const handleDetail = (row) => {
  detail.value = row
  detailDialogVisible.value = true
}

// 积分操作按钮点击
const handlePoints = (row) => {
  pointsForm.value = {
    memberId: row.id,
    name: row.name,
    currentPoints: row.points,
    type: 1,
    points: 0,
    remark: ''
  }
  pointsDialogVisible.value = true
}

// 提交积分操作
const submitPoints = async () => {
  if (!pointsFormRef.value) return
  
  await pointsFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        await updateMemberPoints(pointsForm.value)
        ElMessage.success('操作成功')
        pointsDialogVisible.value = false
        handleQuery()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 禁用按钮点击
const handleDisable = async (row) => {
  try {
    await ElMessageBox.confirm('确认禁用该会员吗？', '提示', {
      type: 'warning'
    })
    
    await updateMemberStatus(row.id, { status: 0 })
    ElMessage.success('禁用成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('禁用失败:', error)
      ElMessage.error('禁用失败')
    }
  }
}

// 启用按钮点击
const handleEnable = async (row) => {
  try {
    await ElMessageBox.confirm('确认启用该会员吗？', '提示', {
      type: 'warning'
    })
    
    await updateMemberStatus(row.id, { status: 1 })
    ElMessage.success('启用成功')
    handleQuery()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启用失败:', error)
      ElMessage.error('启用失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList()
}

// 页码改变
const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList()
}

onMounted(() => {
  handleQuery()
})
</script>

<style lang="scss" scoped>
.member-container {
  padding: 20px;
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .statistics-cards {
    margin-bottom: 20px;
    
    .statistics-content {
      text-align: center;
      
      .amount {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin: 10px 0;
      }
      
      .label {
        font-size: 14px;
        color: #909399;
      }
    }
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
  
  .dialog-footer {
    text-align: right;
  }
  
  .detail-section {
    margin-top: 20px;
    
    .section-title {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 10px;
      color: #303133;
    }
  }
}
</style> 